package com.heima.search.service.impl;

import com.baomidou.mybatisplus.extension.api.R;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.pojos.ApUserSearch;
import com.heima.search.service.ApUserSearchService;
import com.heima.utils.thread.ApThreadLocalUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class ApUserSearchServiceImpl implements ApUserSearchService {


    @Autowired
    private MongoTemplate mongoTemplate;


    /**
     * 删除搜索记录
     *
     * @param apUserSearch
     * @return
     */
    @Override
    public ResponseResult del(ApUserSearch apUserSearch) {

        if(apUserSearch==null || StringUtils.isBlank(apUserSearch.getId())){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        ApUser apUser = ApThreadLocalUtil.get();
        if(apUser==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        mongoTemplate.remove(Query.query(Criteria.where("id").is(apUserSearch.getId())), ApUserSearch.class);

        return ResponseResult.okResult(null);
    }

    /**
     * 加载用户的搜索记录
     *
     * @param userSearchDto
     * @return
     */
    @Override
    public ResponseResult load(UserSearchDto userSearchDto) {

        if(userSearchDto==null){
            return  ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        int pageSize=userSearchDto.getPageSize();
        if(pageSize<0 || pageSize>10){
            pageSize=10;
        }

        ApUser apUser = ApThreadLocalUtil.get();
        if(apUser==null){
            ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }


        Query query = Query.query(Criteria.where("userId").is(apUser.getId()));
        query.with(Sort.by(Sort.Order.desc("createdTime")));
        query.limit(pageSize);


        List<ApUserSearch> apUserSearches = mongoTemplate.find(query, ApUserSearch.class);


        return ResponseResult.okResult(apUserSearches);
    }

    /**
     * 保存用户搜索的关键字s
     *
     * @param searchWords
     */
    @Override
    @Async
    public void saveKeyword(String searchWords,Integer userId) {


        //1、查询当前用户是否搜索过该关键词
        Query query = Query.query(Criteria.where("keyword").is(searchWords).and("userId").is(userId));
        ApUserSearch apUserSearch = mongoTemplate.findOne(query, ApUserSearch.class);

        //2、如果搜索过，则将搜索日期进行更新
        if(apUserSearch!=null){
            apUserSearch.setCreatedTime(new Date());
            mongoTemplate.save(apUserSearch);
            return;
        }

        //2、判断当前用户的搜索关键字是否超过10条

        List<ApUserSearch> list = mongoTemplate.find(Query.query(Criteria.where("userId").is(userId)).with(Sort.by(Sort.Order.desc("createdTime"))), ApUserSearch.class);

        //2.1如果小于10条，则直接添加
        if(list!=null && list.size()>=10){
            ApUserSearch apUserSearch1 = list.get(list.size() - 1);
            mongoTemplate.remove(Query.query(Criteria.where("id").is(apUserSearch1.getId())), ApUserSearch.class) ;  //删除最早的搜索记录
        }

        ApUserSearch userSearch = new ApUserSearch();
        userSearch.setCreatedTime(new Date());
        userSearch.setKeyword(searchWords);
        userSearch.setUserId(userId);
        mongoTemplate.save(userSearch);


    }
}
